package com.weather.service;

import com.weather.common.utils.Base64;
import com.weather.common.utils.SerializeUtils;
import com.weather.domain.ApiRespones;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: htc
 * @date: Created in 15:27 2018/5/4.
 */
@Service
public class WetherServiceImpl implements WeatherService {
    private final static long TIME_OUT = 1800;

    private final static Logger log = LoggerFactory.getLogger(WetherServiceImpl.class);

    @Value("${weather.uri}")
    private String uri;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ApiRespones getWeather(String cityName) throws IOException, ClassNotFoundException, InterruptedException {
        ApiRespones data = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //先查缓存
        if (stringRedisTemplate.hasKey(cityName)) {
            log.info("read redis !");
            String body = ops.get(cityName);
            data = (ApiRespones) SerializeUtils.deSerialize(Base64.decode(body));
        } else {
            log.info("write redis");
            data = restTemplate.getForObject(uri + cityName, ApiRespones.class);
            while (data.getStatus() != 200){
                Thread.sleep(2000);
                this.getWeather(cityName);
            }
            //数据写入缓存
            ops.set(cityName, Base64.encode(SerializeUtils.serialize(data)), TIME_OUT, TimeUnit.SECONDS);
        }
        return data;
    }

    /**
     * 缓存天气数据
     * @param cityName
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @Override
    public void syncDataByCityName(String cityName) throws IOException, ClassNotFoundException {
        this.cacheWeatherData(cityName);
    }

    /**
     * 缓存天气数据
     *
     * @param cityName
     */
    private void cacheWeatherData(String cityName) throws IOException, ClassNotFoundException {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        log.info("write redis");
        ApiRespones data = restTemplate.getForObject(uri + cityName, ApiRespones.class);
        //数据写入缓存
        ops.set(cityName, Base64.encode(SerializeUtils.serialize(data)), TIME_OUT, TimeUnit.SECONDS);
    }
}
